import ldap, { Client } from "ldapjs";
import { Router } from "express";
import { logger } from "../../utils";
import { IreturnObj } from "../../types";
import { JWT } from "../../utils/token";
import { Ioracle } from "../../types";
import { IcallbackFn } from "../../types";
import { decrypt } from "../../utils/privateKey";

interface ServerList {
  [key: string]: string;
}

const serverList: ServerList = {
  xdomain: "ldap://10.2.220.1",
  pdomain: "ldap://10.1.220.1",
  qdomain: "ldap://10.9.220.1",
  sdomain: "ldap://10.6.220.1",
};

export default (router: Router, oracle: Ioracle, callbackFn: IcallbackFn) => {
  router.post("/login", (req, res) => {
    let { username, password } = req.body;
    password = decrypt(password);
    let result: IreturnObj;
    const domain = username.substr(0, 7);
    //只对用户账号是否存在及密码错误做验证，其他验证在前端执行
    const serverName = serverList[domain as keyof ServerList];
    const client: Client = ldap.createClient({
      url: serverName,
    });
    //
    client.bind(username, password, function (err) {
      if (err) {
        result = {
          code: 0,
          message: "用戶不存在或密碼錯誤",
          data: [{ msg: "用戶不存在或密碼錯誤" }],
        };
        logger.info(username + " 验证失败");
        res.send(JSON.stringify(result));
      } else {
        //生成token
        const token = JWT.createtoken(
          { username: username, password: password },
          "120min"
        );

        result = {
          code: 200,
          message: "驗證成功",
          data: [token],
        };
        res.send(result);
      }
      client.unbind(function (err) {
        if (err) {
          logger.error("Error in unbinding: ", err);
          //console.log('Error in unbinding: ', err);
        } else {
          logger.info("Successfully unbound");
        }
      });
      //res.send(JSON.stringify(result))
    });
  });

  router.post("/userInfo", (req, res) => {
    let { username } = req.body;
    let sql = "select chinese_name,dept,work_num from user_info_n";
    sql += " where account = lower('" + username + "')";
    sql += " and job_status = 'employed'";
    callbackFn(res, oracle.connChaos, { sql });
  });

  router.post("/mutelogin", (req, res) => {
    let { username, password } = req.body;
    password = decrypt(password);
    let result: IreturnObj;

    let sql = ` select * from user_info_n where account = '${username}'`;
    oracle
      .connChaos({ sql })
      .then((resultdata) => {
        if (resultdata.data.length > 0) {
          if (password === "compeq.gd.cn") {
            const token = JWT.createtoken(
              { username: username, password: password },
              "120min"
            );

            result = {
              code: 200,
              message: "驗證成功",
              data: [token],
            };
            res.send(result);
          } else {
            result = {
              code: 0,
              message: "密碼錯誤",
              data: [{ msg: "用戶不存在或密碼錯誤" }],
            };
            res.send(JSON.stringify(result));
          }
        }
        else{
           res.send(JSON.stringify({code:402,message:"沒有此用戶"}))
        }
      })
      .catch((err) => {
        res.send({ code: 0, message: err });
      });
  });
  return router;
};
